import React, { Component } from 'react'

import { Row, Col, Modal, message, Form, Table, Space, Button, Popconfirm, Select, Input } from "antd"
import { fetchList, createCategory, updateCategory, deleteCategory } from '@/api/category'


const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
};


const { Option } = Select;

class CategoryTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false
        }
        // 获取表格数据
        this.getCategoryList();
    }
    async componentDidMount() {

    }
    formRef = React.createRef();
    columns = [
        {
            title: '分类名称',
            dataIndex: 'className',
            key: 'className',
        },
        {
            title: '分类ID',
            dataIndex: 'classId',
            key: 'classId',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (text) => {
                return <Space size="middle">
                    <Popconfirm
                        title="确定删除吗?"
                        okText="确定"
                        cancelText="取消"
                        onConfirm={(e) => this.deleteCategory(text)}
                    >
                        <button type="link" >删除</button>
                    </Popconfirm>
                    <button type="link" onClick={() => this.editCategory(text)}>编辑</button>
                </Space>
            },
        },
    ];
    /**
     * 获取分类列表
     */
    getCategoryList = async () => {
        const res = await fetchList({ page: 1, size: 20 });
        if (res.code === 0) {
            const { list, pageSize, currentPage, totalCount } = res.data;
            this.setState({
                list,
                pageSize,
                currentPage,
                totalCount
            })
        }
    }
    // 创建分类
    createCategory = () => {
        this.setState({
            visible: true,
            classId: ''
        }, () => {
            // 在回调中设置值，否则拿不到表单实例
            this.formRef.current.resetFields();
        })
    }
    /**
     * 删除分类
     * @param {*} text 
     */
    deleteCategory = async (text) => {
        const res = await deleteCategory(text);
        if (res.code !== 0) return message.error(res.msg);
        message.success("删除成功");
        this.getCategoryList();
    }
    // 编辑分类
    editCategory = (text) => {
        let { parentId } = text;
        if (parentId === -1) {
            parentId = ""
        }
        // 设置id,以及回显
        this.setState({
            visible: true,
            classId: text.classId
        }, () => {
            // 在回调中设置值，否则拿不到表单实例
            this.formRef.current.setFieldsValue({ ...text, parentId });
        })

    }
    // 分页
    onChange = (args) => {

    }

    handleCancel = () => {
        this.setState({
            visible: false
        })
    }
    handleCreate = async (val) => {
        const res = await createCategory(val);
        if (res.code === 0) {
            message.success("创建分类成功");
            this.getCategoryList();
            this.setState({
                visible: false
            })
        } else {
            message.error(res.msg);
        }
    }

    handleUpdate = async (val) => {
        const res = await updateCategory(val);
        if (res.code === 0) {
            message.success("更新分类成功");
            this.setState({
                visible: false
            })
        } else {
            message.error(res.msg);
        }
    }
    handleOk = () => {
        this.formRef.current.validateFields().then(async (val) => {
            const { classId } = this.state;
            console.log('====================================');
            console.log(classId);
            console.log('====================================');
            if (!classId) return this.handleCreate(val);
            this.handleUpdate({ ...val, classId });

        })
    };
    render() {
        const { list = [], totalCount, visible, classId } = this.state;
        return (
            <>
                <Row >
                    <Col span={6}>
                        <Button type="primary" onClick={this.createCategory}>创建分类</Button>
                    </Col>
                </Row>
                <br />
                <Table
                    rowKey="id"
                    bordered
                    dataSource={list}
                    columns={this.columns}
                    onChange={this.onChange}
                    pagination={{
                        total: totalCount,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条`
                    }}
                />
                {/* modal */}
                <Modal title="创建分类" visible={visible} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <Form
                        {...formItemLayout}
                        ref={this.formRef}
                        labelAlign="right"
                    >
                        <Form.Item label="分类名称" name="className" rules={[{ required: true }]}>
                            <Input allowClear placeholder="请输入分类名称" />
                        </Form.Item>
                        <Form.Item label="父分类" name="parentId" >
                            {/* 编辑的时候无法修改父分类，腾讯云点播有点坑 */}
                            <Select
                                placeholder="请选择父分类，不选默认为一级分类"
                                allowClear
                                disabled={!!classId}
                            >
                                {
                                    list.map((category) => <Option key={category.id} value={category.classId}>  {category.className} </Option>)
                                }
                            </Select>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
        );
    }
}

export default CategoryTable;